package com.second.controller;

import com.second.moudle.Result;
import com.second.util.OSSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Controller
public class UpLoadController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OSSUtil ossUtil;

    /**
     * 请求转发
     * @return
     */
    @RequestMapping("/upload")
    public String upload(){
        return "upload";
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public Result uploadimg(@RequestParam("file") MultipartFile file){

        logger.info("文件上传");
        String FileName = file.getOriginalFilename();
        System.out.println(FileName);
   try {
      if (null != file){
        if (!"".equals(FileName.trim())) {
            File newFile = new File("src/main/webapp/imgs/oss/"+FileName);
            FileOutputStream outputStream = new FileOutputStream(newFile);
            outputStream.write(file.getBytes());
            outputStream.close();
            file.transferTo(newFile.getAbsoluteFile());
            // 上传到OSS
            ossUtil.upLoad(newFile);
            }
         }
      }catch (Exception e){
       e.printStackTrace();
     }
          return new Result("200", "成功","上传成功");
   }

    /**
     * 多文件
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/uploadFileList/{userId}/{shopId}")
    public Result uploadImgList(@RequestParam("file") MultipartFile file,
                                @PathVariable(name = "userId") Integer userId,
                                @PathVariable(name = "shopId") Integer shopId){

        logger.info("文件上传");
        String FileName = file.getOriginalFilename();
        System.out.println(FileName);
        try {
            if (null != file){
                if (!"".equals(FileName.trim())) {
                    File newFile = new File("src/main/webapp/imgs/oss/"+FileName);
                    FileOutputStream outputStream = new FileOutputStream(newFile);
                    outputStream.write(file.getBytes());
                    outputStream.close();
                    file.transferTo(newFile.getAbsoluteFile());
                    // 上传到OSS
                    ossUtil.upLoadList(newFile,userId,shopId);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result("200", "成功","上传成功");
    }
}
